package com.example.project_stm32;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;


        import androidx.annotation.NonNull;

import android.os.Handler;
        import android.util.Log;
        import android.widget.Button;
        import android.widget.TextView;
        import android.widget.Toast;


import com.example.project_stm32.ku.DeviceData;

import org.json.JSONException;
        import org.json.JSONObject;

        import java.io.IOException;

        import okhttp3.Call;
        import okhttp3.Callback;
        import okhttp3.MediaType;
        import okhttp3.Request;
        import okhttp3.RequestBody;
        import okhttp3.Response;
        import okhttp3.OkHttpClient;

public class MainActivity extends AppCompatActivity {
    TextView temperature;
    TextView humidity;
    Button btn_low;
    Button btn_medium;
    Button btn_high;
    Button btn_off;
    Button btn_on;
    private final OkHttpClient client = new OkHttpClient();
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        temperature=findViewById(R.id.temperature_text);
        humidity=findViewById(R.id.humidity_text);
        btn_low=findViewById(R.id.btn_low);
        btn_medium=findViewById(R.id.btn_medium);
        btn_high=findViewById(R.id.btn_high);
        btn_off=findViewById(R.id.btn_off);
        btn_on=findViewById(R.id.btn_on);

        btn_high.setOnClickListener(v->controlHigh());
        btn_medium.setOnClickListener(v->controlMedium());
        btn_low.setOnClickListener(v->controlLow());
        btn_off.setOnClickListener(v->controlOff());
        btn_on.setOnClickListener(v->controlOn());

        startTemperaturePolling();//启动温度轮询

    }

    void controlHigh() { sendStateToServer(3); }
    void controlMedium() { sendStateToServer(2); }
    void controlLow() { sendStateToServer(1); }
    void controlOff() { sendStateToServer(0); }
    void controlOn(){sendStateToServer(4);}

    // 状态发送方法
    private void sendStateToServer(int state) {
        JSONObject json = new JSONObject();
        try {
            json.put("state", state);

            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json.toString()); // 注意参数顺序

            Request request = new Request.Builder()
                    .url("http://192.168.43.170:8080/api/stm32/state")
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    runOnUiThread(() ->
                            Toast.makeText(MainActivity.this, "状态发送失败", Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    // 处理响应...
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 温湿度轮询方法
    private void startTemperaturePolling() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                fetchTemperatureAndHumidity();
                handler.postDelayed(this, 5000); // 5秒轮询一次
            }
        }, 5000);
    }

    // 获取温湿度数据
    private void fetchTemperatureAndHumidity() {
        Request request = new Request.Builder()
                .url("http://192.168.43.170:8080/api/stm32/sensordata") // 替换实际API地址
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("API", "数据获取失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    JSONObject json = new JSONObject(jsonData);
                    System.out.println(request);

                    DeviceData tandh = new DeviceData();
                    tandh.setTemp(json.getInt("temperature"));
                    tandh.setHumid(json.getInt("humidity"));

                    runOnUiThread(() -> {
                        temperature.setText(tandh.getTemp() + "°C");
                        humidity.setText(tandh.getHumid() + "%RH");
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("API", "JSON解析失败", e);
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null); // 停止轮询
    }
}





